package com.qtenv.datasync.worker.tuoanxin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qtenv.datasync.api.tuoanxin.TuoAnXinApi;
import com.qtenv.datasync.base.DataSyncer;
import com.qtenv.datasync.constant.AppConstants;
import com.qtenv.datasync.service.entity.TerminalHistoryData;
import com.qtenv.datasync.service.entity.Terminals_bf;
import com.qtenv.datasync.service.entity.tuoanxin.TAXTerminalHistoryData;
import com.qtenv.datasync.service.service.TerminalsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName TAXDataSyncWorker
 * @Author CBL
 * @Date 2022/2/24 14:52
 **/
@Component
public class TAXDataSyncWorker extends DataSyncer {
    @Autowired
    private TerminalsService terminalsService;

    public TAXDataSyncWorker() {
        super("拓安信");
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryData(String tenantId, String strStartTime, String strEndTime) {
        List<Terminals_bf> terminalsList = terminalsService.findMasTerminalsByTenantAndSupplier(tenantId, AppConstants.TAX_SUPPLIER_ID);
        return this.doGetTerminalHistoryData(tenantId, terminalsList, strStartTime, true);
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryDataForTerminal(Terminals_bf terminals, String tenantId, String strStartTime, String strEndTime) {
        return super.getTerminalHistoryDataForTerminal(terminals, tenantId, strStartTime, strEndTime);
    }

    @Override
    public List<TerminalHistoryData> getTerminalHistoryData(String tenantId, List<String> terminalIdList, String strStartTime, String strEndTime) {
//        List<Terminals> terminalsList = terminalsService.list(new QueryWrapper<Terminals>().eq("tenant_id", tenantId).in("TerminalID", terminalIdList));
//        System.out.println(JSON.toJSONString(terminalsList));
//        if (CollectionUtil.isNotEmpty(terminalsList)) {
//            terminalsList.forEach(item -> item.setTerminalID(item.getTerminalID().substring(10)));
//        }
        List<Terminals_bf> terminalsList = new ArrayList<>();
        terminalIdList.forEach(tid -> {
            Terminals_bf terminals = new Terminals_bf();
            terminals.setTerminalID(tid);
            terminalsList.add(terminals);
        });
        return this.doGetTerminalHistoryData(tenantId, terminalsList, strStartTime, false);
    }

    public List<TerminalHistoryData> doGetTerminalHistoryData(String tenantId, List<Terminals_bf> terminalsList, String strStartTime, boolean filter) {
        if (filter) {
            // 过滤朱村街的数据
            terminalsList = terminalsList.stream().filter(item ->
                            item.getTerminalName().contains("博皇家居") ||
                                    item.getTerminalName().contains("朱村") ||
                                    item.getTerminalInstallAddr().contains("朱村") ||
                                    item.getTerminalName().contains("宁西") ||
                                    item.getTerminalInstallAddr().contains("宁西"))
                    .collect(Collectors.toList());
        }
//        System.out.println(JSONUtil.toJsonStr(terminalsList));
        if (CollectionUtil.isNotEmpty(terminalsList)) {
            String startTime = (strStartTime == null ? LocalDate.now().toString() + "00:00" : strStartTime);
//            System.out.println(startTime);

            int size = terminalsList.size();
            int pageSize = AppConstants.TAX_PAGE_SIZE;
            int numberSize = AppConstants.TAX_NUMBER_SIZE;
            int page = size / pageSize + (size % pageSize == 0 ? 0 : 1);

//            System.out.println("terminalsList==" + JSON.toJSONString(terminalsList));

            List<TerminalHistoryData> result = CollectionUtil.newArrayList();
            for (int pageNo = 0; pageNo < page; pageNo++) {
                List<Terminals_bf> subList = CollectionUtil.page(pageNo, pageSize, terminalsList);
//                System.out.println("subList==" + JSON.toJSONString(subList));

                List<Map<String, Object>> paramList = CollectionUtil.newArrayList();
                subList.forEach(terminals -> {
//                    System.out.println(terminals.getTerminalID());
                    Map<String, Object> requestMap = MapUtil.newHashMap();

                    requestMap.put("fmaddress", terminals.getTerminalID());
                    requestMap.put("starttime", startTime);
                    requestMap.put("number", numberSize);

                    paramList.add(requestMap);
                });

//                System.out.println(paramList);
                String strData = TuoAnXinApi.GetDeviceData(paramList);
//                System.out.println(strData);
                if (StrUtil.isNotEmpty(strData)) {
                    List<TerminalHistoryData> subHistoryDataList = this.transform(tenantId, strData);
                    if (CollectionUtil.isNotEmpty(subHistoryDataList)) {
                        result.addAll(subHistoryDataList);
                    }
                }
                ThreadUtil.safeSleep(1 * 1000);

                System.out.println("第【" + pageNo + "】次获取数据完成，目前数据总量：" + result.size());
            }

            return result;
        }

        return null;
    }

    private List<TerminalHistoryData> transform(String tenantId, String strData) {
        List<TerminalHistoryData> result = CollectionUtil.newArrayList();

        JSONArray jsonArray = JSON.parseObject(strData).getJSONArray("body");
        jsonArray.forEach(json -> {
            JSONObject jsonObject = JSON.parseObject(json.toString());
            if (jsonObject.getIntValue("code") == 0) {
                String terminalID = jsonObject.getString("fmaddress");
                List<TAXTerminalHistoryData> taxTerminalHistoryDataList = JSON.parseArray(jsonObject.getString("values"), TAXTerminalHistoryData.class);
                taxTerminalHistoryDataList.forEach(taxTerminalHistoryData -> {
                    TerminalHistoryData terminalHistoryData = new TerminalHistoryData();
                    BeanUtil.copyProperties(taxTerminalHistoryData, terminalHistoryData);
                    terminalHistoryData.setTenant_id(tenantId);
                    terminalHistoryData.setSupplierID(AppConstants.TAX_SUPPLIER_ID);
                    terminalHistoryData.setTerminalID(terminalID);

                    result.add(terminalHistoryData);
                });
            }
        });

        return result;
    }

    @Override
    public List<TerminalHistoryData> doGetTerminalHistoryDataFromTerminal(Terminals_bf terminals, String tenantId, String tids, String strStartTime, String strEndTime) {
        return super.doGetTerminalHistoryDataFromTerminal(terminals, tenantId, tids, strStartTime, strEndTime);
    }

    @Override
    public List<TerminalHistoryData> transformFromTerminal(Terminals_bf terminals, String tenantId, String strData) {
        return super.transformFromTerminal(terminals, tenantId, strData);
    }

    public static void main(String[] args) {
//        TAXDataSyncWorker worker = new TAXDataSyncWorker();
//        System.out.println(JSON.toJSONString(worker.getTerminalHistoryData("2022-03-17 00:00", null), true));

        // 拓安信数据接口拉取当天数据-有数据

//        String sp = " 00:00:00";
//        LocalDate s = LocalDate.parse("2022-06-17");
//        String ep = " 23:59:59";
//        LocalDate e = LocalDate.parse("2022-06-22");
//        while (s.isBefore(e) || s.isEqual(e)) {
//            worker.syncTerminalHistoryData(s.toString() + sp, s.toString() + ep);
//            s = s.plusDays(1L);
//        }
    }
}
